import axios from 'axios'

import { ElMessage } from 'element-plus'

const service = axios.create({
    baseURL: 'api',
    timeout: 5000,
})

service.interceptors.request.use(
    (config) => {
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response) => {
        const res = response.data
        if (res.code !== 0) {
            ElMessage.error({
                message: res.message || 'Error',
                duratons: 5 * 1000,
            })
            return
        }
        return res
    },
    (error) => {
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
            ElMessage.error({
                message: '请求服务器超时',
                duratons: 5 * 1000,
            })
        } else {
            return Promise.reject('请求服务器错误')
        }
    }
)

export default service
